//
//  AppDelegate.m
//  DCTCustomer
//
//  Created by 姚宗超 on 14/9/9.
//  Copyright (c) 2014年 姚宗超. All rights reserved.
//

#import "AppDelegate.h"
#import "MPNotificationConstant.h"
#import "MPAppConstant.h"

// UserDefault
#import "MPUserDefaultHelper.h"

// Log相关
#import "DDFileLogger.h"
#import "DDASLLogger.h"
#import "DDTTYLogger.h"
#import "MPDirectoryHelper.h"

// Baidu Push
#import "BPush.h"
#import "JSONKit.h"

// UI Tab
#import "RDVTabBarController.h"
#import "RDVTabBarItem.h"
#import "RDVTabBar.h"
#import "MPBidTableViewContainer.h"
#import "MPNewsTableViewController.h"

// TOOLS
#import "UIImage+Common.h"

// 网络相关
#import "MPNetworkService.h"
#import "MPDeviceObject.h"

// Test
#import "MPGuideViewController.h"
#import "MPNavigationViewController.h"

@interface AppDelegate () <BPushDelegate>

@end

@implementation AppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    // 注册log功能
    [self setupLogger];
    
    // 加载UserDefault
    [MPUserDefaultHelper readParamFromUserDefault];
    
    //注册通知
    if (IOS8_OR_LATER) {
        UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:(UIRemoteNotificationTypeBadge
                                                                                             |UIRemoteNotificationTypeSound
                                                                                             |UIRemoteNotificationTypeAlert) categories:nil];
        [[UIApplication sharedApplication] registerUserNotificationSettings:settings];
    }
    else {
        [application registerForRemoteNotificationTypes:UIRemoteNotificationTypeAlert
         | UIRemoteNotificationTypeBadge
         | UIRemoteNotificationTypeSound];
    }
    
    // 定制UI
    [self configUIAppearence];

    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    self.window.backgroundColor = [UIColor whiteColor];
    if ([MPDeviceObject sharedInstance].isFirstLogin) {
        // 第一次进入,注册百度推送
        [BPush setupChannel:launchOptions];
        [BPush setDelegate:self];
        MPGuideViewController* vc = [[MPGuideViewController alloc] initWithCompletionHandler:^(eMPVisitorSubscribeType type) {
            self.window.rootViewController = [self createTabBarWithVisitType:type];
        }];
        self.window.rootViewController = vc;
    }
    else
    {
        self.window.rootViewController = [self createTabBarWithVisitType:eMPVisitorSubscribeTypeRefresh];
    }

    [self.window makeKeyAndVisible];
    return YES;
}

#pragma mark -- UI
- (RDVTabBarController *)createTabBarWithVisitType:(eMPVisitorSubscribeType)type
{
    // 我要抢标页
    MPBidTableViewContainer* bid = [[MPBidTableViewContainer alloc] initWithVisitType:type];
    MPNavigationViewController* bidNav = [[MPNavigationViewController alloc] initWithRootViewController:bid];
    
    // 资讯页
    MPNewsTableViewController* new = [[MPNewsTableViewController alloc] init];
    MPNavigationViewController* newNav = [[MPNavigationViewController alloc] initWithRootViewController:new];
    
    RDVTabBarController *tabBarController = [[RDVTabBarController alloc] init];
    [tabBarController setViewControllers:@[bidNav, newNav]];
    
    [self customizeTabBarForController:tabBarController];
    
    return tabBarController;
}

- (void)configUIAppearence
{
    UINavigationBar *navigationBarAppearance = [UINavigationBar appearance];
    [navigationBarAppearance setBackgroundImage:[UIImage imageFromColor:[UIColor colorWithHexString:kTopBarBgColor]] forBarMetrics:UIBarMetricsDefault];
    NSDictionary *textAttributes = @{
                                     NSFontAttributeName: [UIFont systemFontOfSize:20.0],
                                     NSForegroundColorAttributeName: [UIColor whiteColor],
                                     };
    [navigationBarAppearance setTitleTextAttributes:textAttributes];
}

- (void)setupLogger
{
    DDLogFileManagerDefault *fileManager = [[DDLogFileManagerDefault alloc] initWithLogsDirectory:MPLogDir];
    DDFileLogger *fileLogger = [[DDFileLogger alloc] initWithLogFileManager:fileManager];
    fileLogger.rollingFrequency = 60 * 60 * 24; // 24 hour rolling
    fileLogger.logFileManager.maximumNumberOfLogFiles = 7;
    [DDLog addLogger:fileLogger];
    [DDLog addLogger:[DDASLLogger sharedInstance]];
    [DDLog addLogger:[DDTTYLogger sharedInstance]];
}

- (BOOL)isTopViewController:(NSString *)className
{
    UIViewController *pVC = self.window.rootViewController;
    if ([pVC isKindOfClass:[UINavigationController class]]) {
        UINavigationController* nav = (UINavigationController *)pVC;
        return [className isEqualToString:[nav.visibleViewController className]];
    }
    else if ([pVC isKindOfClass:[UITabBarController class]])
    {
        UITabBarController* tab = (UITabBarController *)pVC;
        return [className isEqualToString:[tab.selectedViewController className]];
    }
    else if ([pVC isKindOfClass:[RDVTabBarController class]])
    {
        RDVTabBarController* rdv = (RDVTabBarController *)pVC;
        UIViewController* vc = [rdv selectedViewController];
        if ([vc isKindOfClass:[UINavigationController class]]) {
            UINavigationController* nav = (UINavigationController *)vc;
            return [className isEqualToString:[nav.visibleViewController className]];
        }
        return [className isEqualToString:[pVC className]];
    }
    else
    {
        return NO;
    }
}

- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
    [MPUserDefaultHelper saveParamToUserDefault];
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
    // Saves changes in the application's managed object context before the application terminates.
    [MPUserDefaultHelper saveParamToUserDefault];
}

#pragma mark - PUSH Notification
#pragma mark - ios push
- (void)application:(UIApplication *)application didRegisterUserNotificationSettings:(UIUserNotificationSettings *)notificationSettings NS_AVAILABLE_IOS(8_0)
{
    [application registerForRemoteNotifications];
}

// Called when your app has been activated by the user selecting an action from a local notification.
// A nil action identifier indicates the default action.
// You should call the completion handler as soon as you've finished handling the action.
- (void)application:(UIApplication *)application handleActionWithIdentifier:(NSString *)identifier forLocalNotification:(UILocalNotification *)notification completionHandler:(void(^)())completionHandler NS_AVAILABLE_IOS(8_0)
{
    
}

// Called when your app has been activated by the user selecting an action from a remote notification.
// A nil action identifier indicates the default action.
// You should call the completion handler as soon as you've finished handling the action.
- (void)application:(UIApplication *)application handleActionWithIdentifier:(NSString *)identifier forRemoteNotification:(NSDictionary *)userInfo completionHandler:(void(^)())completionHandler NS_AVAILABLE_IOS(8_0)
{
    
}

- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    KDLogInfo(@"deviceToken:%@",deviceToken);
    [BPush registerDeviceToken: deviceToken];
    [BPush bindChannel];//异步的
}

- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error NS_AVAILABLE_IOS(3_0)
{
    
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
    KDLogInfo(@"Receive Notify: %@", [userInfo JSONString]);
    if ( application.applicationState != UIApplicationStateActive ) {
        //程序在后台运行过程中受到推送通知
        [self handlePushWhenBackLaunch:userInfo];
    } else {
        //程序为在运行状态受到推送通知
        [self handlePushWhenForeLaunch:userInfo];
    }
    
    [BPush handleNotification:userInfo];
}

-(void)handlePushWhenBackLaunch:(NSDictionary*)data
{
    NSString *pushType = [data objectForKey:@"type"];
//    if([pushType isEqualToString:FPPushTypeProduct]){
//        
//        NSString *proId = [data objectForKey:@"id"];
//        if(proId){
//            NSString *status = [data objectForKey:@"status"];
//            MProduct *product = [[MProduct alloc] init];
//            product.productID = proId;
//            product.status = [status intValue];
//            
//            [self handlePushProduct:product];
//        }
//    }
    //清除已读通知
    [UIApplication sharedApplication].applicationIconBadgeNumber = 0;
    [[UIApplication sharedApplication]cancelAllLocalNotifications];
}

-(void)handlePushWhenForeLaunch:(NSDictionary*)data
{
    NSString *pushType = [data objectForKey:@"type"];
//    if([pushType isEqualToString:FPPushTypeProduct]){
//        NSString *proId = [data objectForKey:@"id"];
//        if(proId){
//            NSString *status = [data objectForKey:@"status"];
//            NSString *title = [data objectForKey:@"title"];
//            NSDictionary *aps = [data objectForKey:@"aps"];
//            NSString *msg = [aps objectForKey:@"alert"];
//            
//            pushProduct = [[MProduct alloc] init];
//            pushProduct.productID = proId;
//            pushProduct.status = [status intValue];
//            if(!pushAlert.visible){
//                pushAlert = [[CustomAlertView alloc] initWithTitle:title message:msg confirmButtonTitle:@"查看" cancelButtonTitle:@"关闭" delegate:self];
//                [[CustomAlertBackgroundWindow sharedBackgroundWindow] removeAllAlerts];
//                [pushAlert show];
//            }
//        }
//    }
}


#pragma mark - BPushDelegate
- (void) onMethod:(NSString*)method response:(NSDictionary*)data {
    NSDictionary* res = [[NSDictionary alloc] initWithDictionary:data];
    if ([BPushRequestMethod_Bind isEqualToString:method]) {
        int returnCode = [[res valueForKey:BPushRequestErrorCodeKey] intValue];
        if (returnCode == BPushErrorCode_Success) {
            NSString *userid = [res valueForKey:BPushRequestUserIdKey];
            NSString *channelid = [res valueForKey:BPushRequestChannelIdKey];
            NSString* appId = [res valueForKey:BPushRequestAppIdKey];
            [MPDeviceObject sharedInstance].bRegisterAppId = appId;
            [MPDeviceObject sharedInstance].bRegisterChannelId = channelid;
            [MPDeviceObject sharedInstance].bRegisterUserId = userid;
            // 注册设备
            [MPNetworkService registerDeviceWithObject:[MPDeviceObject sharedInstance] onComletion:^(NSInteger errorNum, NSDictionary *info, MPError *errorMsg) {
                if (errorMsg) {
                    [[MPRemindHelper sharedInstance] showHudOnWindowWithTitleText:errorMsg.titleForError duration:1.0f];
                    return ;
                }
                
                [MPDeviceObject sharedInstance].isFirstLogin = NO;
            }];
        }
    } else if ([BPushRequestMethod_Unbind isEqualToString:method]) {
        int returnCode = [[res valueForKey:BPushRequestErrorCodeKey] intValue];
        if (returnCode == BPushErrorCode_Success) {
            //解绑推送账号
            [MPDeviceObject sharedInstance].isFirstLogin = YES;
        }
    }
    DLog( @"%@push__ return: \n%@", method, [data description]);
}

#pragma mark - share callback
/**
 这里处理新浪微博SSO授权之后跳转回来，和微信分享完成之后跳转回来
 */
//- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation
//{
//    return  [UMSocialSnsService handleOpenURL:url wxApiDelegate:nil];
//}

#pragma mark - UMUpdate Delegate
//- (void)updateMethod:(NSDictionary *)appInfo {
//    if([@"YES" isEqualToString:[appInfo objectForKey:@"update"]]){
//        NSArray  * logArr= [[appInfo objectForKey:@"update_log"] componentsSeparatedByString:@"###"];
//        NSString *alertTitle = [NSString stringWithFormat:@"发现新版本%@",[appInfo objectForKey:@"version"]];
//        
//        BOOL isRequired = NO;
//        //防止数组越界
//        if (logArr && logArr.count>0) {
//            isRequired = [@"required" isEqual:[logArr objectAtIndex:0]];
//        }
//        NSString *log = nil;
//        if(logArr && logArr.count>1){
//            log =[logArr objectAtIndex:1];
//        }
//        
//        updateAlert = [[CustomAlertView alloc] initWithTitle:alertTitle message:log confirmButtonTitle:@"前往Store下载" cancelButtonTitle:(isRequired?nil:@"下次再说") delegate:self];
//        [updateAlert show];
//        [appInfo setValue:[logArr objectAtIndex:0] forKey:@"type"];
//        _appInfo = appInfo;
//    }
//}


#pragma mark - Methods
- (void)customizeTabBarForController:(RDVTabBarController *)tabBarController
{
    RDVTabBar *tabBar = [tabBarController tabBar];
    [tabBar setFrame:CGRectMake(CGRectGetMinX(tabBar.frame), CGRectGetMinY(tabBar.frame), CGRectGetWidth(tabBar.frame), 49.0f)];
    for (int index = 0; index < [[tabBarController tabBar] items].count; index++) {
        RDVTabBarItem* item = [[[tabBarController tabBar] items] objectAtIndex:index];
        [item setUnselectedTitleAttributes:@{
                                             NSFontAttributeName: [UIFont systemFontOfSize:kContentFontSize],
                                             NSForegroundColorAttributeName: [UIColor colorWithHexString:kTextUnSelectedGrayColor],
                                             }];
        [item setSelectedTitleAttributes:@{
                                           NSFontAttributeName: [UIFont systemFontOfSize:kContentFontSize],
                                           NSForegroundColorAttributeName: [UIColor whiteColor],
                                           }];
        
        [item setBackgroundSelectedImage:[UIImage imageFromColor:[UIColor colorWithHexString:kTabBarNormalBgColor]] withUnselectedImage:[UIImage imageFromColor:[UIColor colorWithHexString:kTabBarSelectedBgColor]]];
        
        if (index == 0) {
            [item setFinishedSelectedImage:[UIImage imageForKey:@"tabbar_bid_icon_selected"] withFinishedUnselectedImage:[UIImage imageForKey:@"tabbar_bid_icon_unSelected"]];
            item.title = @"我要投标";
        }
        
        if (index == 1) {
            [item setFinishedSelectedImage:[UIImage imageForKey:@"tabbar_new_icon_selected"] withFinishedUnselectedImage:[UIImage imageForKey:@"tabbar_new_icon_unSelected"]];
            item.title = @"资讯";
        }
    }
}


@end
